// interface Option {
//   methodOption: "GET" | "POST" | "OPTIONS" | "HEAD" | "PUT" | "DELETE" | "TRACE" | "CONNECT" | undefined;
// }

type requestMethod = "GET" | "POST" | "OPTIONS" | "HEAD" | "PUT" | "DELETE" | "TRACE" | "CONNECT" | undefined;

const request = function (url: string, method: requestMethod, data?: any) {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中',
    })

    let tokenValue: string = '';
    try {
      tokenValue = wx.getStorageSync('tokenValue')
      if (tokenValue) {
        // Do something with return value
      } else {
        console.log('没有获取token')
      }
    } catch (e) {
      // Do something when catch error
    }

    wx.request({
      url: url,
      method: method,
      data: data,
      header: {
        Authtoken: tokenValue
      },
      success(res: any) {
        wx.hideLoading();
        if (res.data && res.data.code && parseInt(res.data.code) == 500) {
          reject(res.data)
        } else if (res.data && res.data.code && parseInt(res.data.code) == 4001) {
          try {
            wx.removeStorageSync('tokenValue');
            wx.reLaunch({
              url: "/pages/login/index"
            })
            wx.showToast({
              title: 'Token无效或已过期',
              icon: 'none',
              duration: 5000
            })
          } catch (e) {
            // Do something when catch error
          }
        } else {
          resolve(res.data)
        }
      },
      fail(err) {
        // 接口调用失败的回调函数
        wx.hideLoading();
        reject(err)
      },
      complete() {
        // 接口调用结束的回调函数
      }
    })
  })
}

export { request }